package com.china08.yxyapi.api.comm.upload;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.china08.yxyapi.model.YxyApiRespModel;
import com.china08.yxyapi.util.ThumbnailsUtil;
import com.china08.yxyapi.util.YXCSPUtil;

@CrossOrigin
@RestController("UploadImgForCkController")
public class UploadImgForCkController {

    @Autowired
    private YXCSPUtil yxcspUtil;

    /**
     * ckeditor上传图片
     * 
     * @param multipartFile
     * @param request
     * @param response
     * @param rbp
     * @throws IOException
     */
    @RequestMapping(value = "/api_yw/comm/uploadImgForCk")
    public void upldImg(@RequestParam(value = "upload") MultipartFile multipartFile, HttpServletRequest request, HttpServletResponse response) throws IOException {
        RespModel respModel = new RespModel();
        String name = multipartFile.getOriginalFilename();
        String filePostfix = FilenameUtils.getExtension(name);
        byte[] bytes = ThumbnailsUtil.perfectForWidth(multipartFile.getBytes(), 640, filePostfix);
        MockMultipartFile newMultipartFile = new MockMultipartFile(multipartFile.getName(), multipartFile.getOriginalFilename(), multipartFile.getContentType(), bytes);
        PrintWriter out = response.getWriter();
        String url = yxcspUtil.push(newMultipartFile);
        String CKEditorFuncNum = request.getParameter("CKEditorFuncNum");
        String s = "<script type=\'text/javascript\'>window.parent.CKEDITOR.tools.callFunction(" + CKEditorFuncNum + ", '" + url + "',''" + ");</script>";
        out.print(s);
        out.flush();
        respModel.setUrl(url);
        respModel.setMessage("上传成功");
    }

    protected static class RespModel extends YxyApiRespModel {
        public String url;

        public String getUrl() {
            return url;
        }

        public void setUrl(String url) {
            this.url = url;
        }
    }
}
